package main
/*
Connect to predefined host via po proxy (proxy.go)
*/
import (
	"net"
	"os"
	"fmt"
	"log"
	//"io/ioutil"
	"time"
)

var connIn *net.TCPConn
var connOut *net.TCPConn

func  openOut() {
	service := "localhost:1400"
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)
  for {
		connOut, err = net.DialTCP("tcp", nil, tcpAddr)
		checkError(err)
		//connOut.SetReadDeadline(time.Now())
		fmt.Println("conn: Open out")
		handleClientOut()
  }
}

func closeConnIn() {
	connIn.Close()
	connIn = nil
}

func closeConnOut() {
	connOut.Close()
	connOut = nil
}

func  openIn() {
	service := "localhost:80"
	fmt.Println("Conn: open in")
	tcpAddr, err := net.ResolveTCPAddr("ip", service)
	checkError(err)

	connIn, err = net.DialTCP("tcp", nil, tcpAddr)
	//connIn.SetReadDeadline(time.Now())
	checkError(err)	
	go handleClientIn()
}

/*Read from Out and send to in*/
func handleClientOut () {
	defer closeConnOut()
	defer fmt.Println("Conn: close out")
	//defer connIn.Close()

	var buf [512]byte
	for {
		n, err := connOut.Read(buf[0:])
		if err != nil {
			return
		}
		fmt.Println(string(buf[0:]))
		if (connIn == nil) {
			openIn()
		} else {
			fmt.Println("In is opened")
		}
		_, err2 := connIn.Write(buf[0:n])
		if err2 != nil {
			return
		}
	}
}

/*Read from in and send to Out- usually to remote browser*/
func handleClientIn () {
	defer closeConnIn()
	defer closeConnOut()
	defer fmt.Println("Conn: close in/OUT")
	var buf [512]byte
	for {
		fmt.Println("Conn: read from server")
		n, err := connIn.Read(buf[0:])
		if err != nil {
			return
		}
		fmt.Println(string(buf[0:]))
		if (connOut != nil) {
			fmt.Println("conn: writing to browser");
			_, err2 := connOut.Write(buf[0:n])
			if err2 != nil {
				return
			}
		} else {
			return
		}
	}
}

func main() {
	log.SetPrefix("conn: ")
	log.Println(time.Now())
	openOut()
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}
